package com.zcl.iweibo;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.netqin.ui.share.sinaweibo.AccessToken;
import com.netqin.ui.share.sinaweibo.DialogError;
import com.netqin.ui.share.sinaweibo.Utility;
import com.netqin.ui.share.sinaweibo.Weibo;
import com.netqin.ui.share.sinaweibo.WeiboException;
import com.netqin.ui.share.sinaweibo.WeiboOAuthListener;
import com.zcl.bean.Task;
import com.zcl.logic.MainService;
import com.zcl.protocol.APPProtocolInterface;
import com.zcl.utils.DialogFactory;
import com.zcl.utils.NqLog;
import com.zcl.utils.Value;

public class WebViewActivity extends Activity implements IWeiboActivity{
	
	public static final String LOGIN_WEIBO = "login_weibo"; 
	public static final String BIND_WEIBO = "bind_weibo";
	public static final String REDIRECT_PAGE = "redirect_page";
	
	private final int DIALOG_LOGINING = 1;
	private final int DIALOG_GETUSER_SUCESS = 2;
	private final int DIALOG_GETUSER_FAILED = 3;
	private AuthSinaListener mListener = new AuthSinaListener();
	private Weibo mWeibo; 
	private Context mContext;
	private String mType;
	public boolean load(final WebView webView,final String url)
	{
		if (TextUtils.isEmpty(url)) {
			return false;
		}
		new Thread()
		{
			@Override
			public void run() {
				webView.loadUrl(url);
			}
		}.start();
		showDialog(DIALOG_LOGINING);
		return true;
	}
	
	public WebView getWebView()
	{
		return (WebView)this.findViewById(R.id.webview_auth);
	}
	
	public TextView getTitleTextView()
	{
		return (TextView)this.findViewById(R.id.textView);
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		
		init();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LOGINING: { // 正在登录中
			ProgressDialog dialog = new ProgressDialog(WebViewActivity.this);
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.setMessage(WebViewActivity.this
					.getString(R.string.text_connecting));
			dialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) { // 取消登录
				// NetTransactionService.getInstance(TAuthDemoActivity.this).cancel();
				}
			});

			return dialog;
		}
		case DIALOG_GETUSER_SUCESS: {
			return DialogFactory.createDialog(WebViewActivity.this, R.string.text_info_tips,
					R.string.text_getuser_success, R.string.text_confirm,
					new OnClickListener() {
						@Override
						public void onClick(View v) {
							removeDialog(DIALOG_GETUSER_SUCESS);
							Intent intent=new Intent(WebViewActivity.this, MainActivity.class);
							startActivity(intent);
							finish();
						}
					});
		}
		case DIALOG_GETUSER_FAILED: {
			return DialogFactory.createDialog(WebViewActivity.this, R.string.text_info_tips,
					R.string.text_getuser_error, R.string.text_confirm,
					new OnClickListener() {
						@Override
						public void onClick(View v) {
							removeDialog(DIALOG_GETUSER_FAILED);
							finish();
						}
					});
		}
		}
		return super.onCreateDialog(id);
	}
    
    @Override
	public void init()
	{
		mContext = this;
		if (!TextUtils.isEmpty(this.getIntent().getStringExtra(REDIRECT_PAGE))) {
			mType = this.getIntent().getStringExtra(REDIRECT_PAGE);
		}
		WebView webView = (WebView)this.findViewById(R.id.webview_auth);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		
		webView.setWebChromeClient(new WebChromeClient(){

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				if (100 == newProgress) {
					removeDialog(DIALOG_LOGINING);
				}
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {
				super.onReceivedTitle(view, title);
				getTitleTextView().setText(title);
			}
		});
		webView.setWebViewClient(new WebViewClient(){
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				NqLog.d("Redirect URL: " + url);
	            // 待后台增加对默认重定向地址的支持后修改下面的逻辑
	            if (url.startsWith(mWeibo.getRedirectUrl())) {
	                handleRedirectUrl(view, url);
	                
	                return true;
	            }
	            return false;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				NqLog.d("onPageStarted URL: " + url);
	            if (url.startsWith(mWeibo.getRedirectUrl())) {
	                handleRedirectUrl(view, url);
	                view.stopLoading();
//	                ((Activity)mContext).finish();
	                return ;
	            }
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				removeDialog(DIALOG_LOGINING);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				removeDialog(DIALOG_LOGINING);
				mListener.onError(new DialogError(description, errorCode, failingUrl));
			}
			
		});
		
		ImageButton closeButton = (ImageButton)findViewById(R.id.btn_close);
		closeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		mWeibo = Weibo.getInstance();
		mWeibo.setupConsumerConfig(Value.CONSUMER_KEY, Value.CONSUMER_SECRET);
		mWeibo.setRedirectUrl(Value.CONSUMER_REDIRECTURL);
		mWeibo.authorize(this, mListener);
		
		//test--start
//		AccessToken accessToken = new AccessToken("2.00FuiQGClNyDBEdeff51033epYuqZC", Value.CONSUMER_SECRET);
//		accessToken.setExpiresIn("77500");
//		Weibo.getInstance().setAccessToken(accessToken);
//		Weibo.getInstance().setUserID("1924909541");
//        Task task = new Task();
//        task.setTaskId(Task.REQUEST_USER);
//        MainService.newTask(task);
        //test--end
	}
	
	private void handleRedirectUrl(WebView view, String url) {
        Bundle values = Utility.parseUrl(url);

        String error = values.getString("error");
        String error_code = values.getString("error_code");

        if (error == null && error_code == null) {
            mListener.onComplete(values);
        } else if (error.equals("access_denied")) {
            // 用户或授权服务器拒绝授予数据访问权限
            mListener.onCancel();
        } else {
            mListener.onWeiboException(new WeiboException(error, Integer.parseInt(error_code)));
        }
    }
	

	class AuthSinaListener implements WeiboOAuthListener {
		
		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String openId = values.getString("uid");
			if (TextUtils.isEmpty(token)) {
				return;
			}
			NqLog.d("access_token : " + token + "  expires_in: "
					+ expires_in);
			
			AccessToken accessToken = new AccessToken(token, Value.CONSUMER_SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);
			Weibo.getInstance().setUserID(openId);
			// TODO::发起和服务器的交互
			requestWeiBoAccount(token, mType);
			// 请求用户信息
			MainService.addActivity(WebViewActivity.this);
            Task task = new Task();
            task.setTaskId(Task.REQUEST_USER);
            MainService.newTask(task);
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
			finish();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			// TODO Auto-generated method stub
			
		}
		
		void requestWeiBoAccount(String accessToken, String type) {
	
		}
	}

	@Override
	public void refresh(Object... objects) {
		MainService.removeActivity(WebViewActivity.this);
		if (objects[0] instanceof Message) {
			Message msg = (Message)objects[0];
			if (APPProtocolInterface.CMD01_GETUSERINFO == msg.arg1) {
				if (Task.REQUEST_USER_FAILED == msg.arg2) {
					showDialog(DIALOG_GETUSER_FAILED);
				}else if (Task.REQUEST_USER_SUCCESS == msg.arg2) {
					showDialog(DIALOG_GETUSER_SUCESS);
					
				}
			}
		}
		
	}
}
